package priv.lhy.ecm.collectorProducer.aftertreatment.record.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import priv.lhy.common.utils.DateUtil;
import priv.lhy.ecm.collectorProducer.aftertreatment.record.IDispose;
import priv.lhy.ecm.collectorProducer.constants.ExceptionType;

import java.io.*;
import java.util.Date;

/**
 * @author: lihy
 * date: 2019/6/29 11:31
 * description: 将上传异常的数据存入文件
 */
@Slf4j
@Component("disposeByFile")
public class DisposeByFile implements IDispose {

    @Value("${upload.keepRecord.path.prefix}")
    private String filePathPrefix;

    @Override
    public void dispose(String msg, String oldFileName, ExceptionType exceptionType) {
        String[] message = msg.split("\\|");
        String userCode = message[1];
        String type = message[2];

        String filePath = filePathPrefix + getPath(exceptionType);

        Writer writer = null;
        try {
            String fileName;
            if (null == oldFileName || oldFileName.equals("")) {
                //以小时为单位分割文件
                fileName = filePath + userCode + "_" + type + "_" + DateUtil.dateCustomStr(new Date(),
                        "yyyyMMddHH");
            } else {
                filePath = filePath + oldFileName.split("/")[0];
                fileName = filePath + "/" + oldFileName.split("/")[1];
            }
            createFile(filePath, false);
            File file = createFile(fileName, true);
            if (!file.exists()) {
                writer = new FileWriter(file);
                writer.write(msg + "\r\n");
            } else {
                writer = new FileWriter(file, true);
                writer.append(msg + "\r\n");
            }
            writer.flush();
            log.error("发生错误，错误类型【" + type + "】，上传数据已记录到" + fileName + "中");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 根据异常类型获取文件路径
     * @param exceptionType
     * @return
     */
    private String getPath(ExceptionType exceptionType) {
        return exceptionType.name() + "/";
    }

    /**
     * 创建文件和文件夹
     *
     * @param fileName
     * @param isFile
     * @return
     * @throws IOException
     */
    private File createFile(String fileName, boolean isFile) throws IOException {
        File file = new File(fileName);
        if (isFile && !file.exists()) {
            file.createNewFile();
        }
        if (!isFile && !file.exists()) {
            file.mkdirs();
        }
        return file;
    }

}
